//
//  BLEConnectViewController.m
//  BLE4.0-SerialPort
//
//  Created by lan on 15/9/22.
//  Copyright © 2015年 lan. All rights reserved.
//

#import "BLEConnectViewController.h"

#import <CoreBluetooth/CoreBluetooth.h>

#import "MBProgressHUD+MJ.h"


@interface BLEConnectViewController () <CBCentralManagerDelegate,UITableViewDataSource, UITableViewDelegate>

/** 蓝牙管理器 */
@property (nonatomic, strong) CBCentralManager *manager;

@property (nonatomic, strong) NSMutableArray *bluetooths;

@end

@implementation BLEConnectViewController

- (NSMutableArray *)bluetooths {
    if ( _bluetooths == nil) {
        _bluetooths = [NSMutableArray array];
    }
    return _bluetooths;
}



- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 初始化蓝牙管理器
    _manager = [[CBCentralManager alloc] initWithDelegate:self queue:nil];
    
    [MBProgressHUD showMessage:@"正在扫描设备..."];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 扫描设备
        [self.manager scanForPeripheralsWithServices:nil options:nil];
        NSLog(@"扫描设备...");
        [MBProgressHUD hideHUD];
        
    });
    
    self.tableView.rowHeight = 80;
}


#pragma mark -  蓝牙管理器代理方法
/**
 *  主设备状态改变，只有在设备正确打开后才能使用
 */
- (void)centralManagerDidUpdateState:(CBCentralManager *)central{
    NSLog(@"蓝牙状态改变");
    /*
     CBCentralManagerStateUnknown = 0,
     CBCentralManagerStateResetting,
     CBCentralManagerStateUnsupported,
     CBCentralManagerStateUnauthorized,
     CBCentralManagerStatePoweredOff,
     CBCentralManagerStatePoweredOn,
     */
    switch (central.state) {
        case CBCentralManagerStateUnknown:
            NSLog(@"CBCentralManagerStateUnknown");
            break;
        case CBCentralManagerStateResetting:
            NSLog(@"CBCentralManagerStateResetting");
            break;
        case CBCentralManagerStateUnsupported:
            NSLog(@"CBCentralManagerStateUnsupported");
            break;
        case CBCentralManagerStateUnauthorized:
            NSLog(@"CBCentralManagerStateUnauthorized");
            break;
        case CBCentralManagerStatePoweredOff:
            NSLog(@"CBCentralManagerStatePoweredOff");
            break;
        case CBCentralManagerStatePoweredOn:
            NSLog(@"CBCentralManagerStatePoweredOn");
            break;
        default:
            break;
    }
    
}

/**
 *  扫描到外设时调用
 */
- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI{
    NSLog(@"扫描到外设");
    
    // 如果发现新的外设，添加到数组中
    if (![self.bluetooths containsObject:peripheral]) {
        [self.bluetooths addObject:peripheral];
    }
    
    // 刷新表格
    [self.tableView reloadData];
    
}



#pragma mark - Table view data source

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.bluetooths.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *ID = @"cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:ID];
    }
    
    CBPeripheral *bluetooth = self.bluetooths[indexPath.row];
    
    cell.textLabel.text = bluetooth.name;
    cell.detailTextLabel.text = [NSString stringWithFormat:@"%@", bluetooth.identifier];
    
    
    cell.textLabel.font = [UIFont systemFontOfSize:25];
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSLog(@"select");
    
    CBPeripheral *bluetooth = self.bluetooths[indexPath.row];
    
    //发送通知
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    dict[@"peripheral"] = bluetooth;

    [[NSNotificationCenter defaultCenter] postNotificationName:@"selectedBluetoothNotification" object:self userInfo:dict];
    [self.navigationController popToRootViewControllerAnimated:YES];
}


@end
